package com.hn.gege.im.modules.im.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hn.gege.im.modules.im.entity.ChatMessage;
import com.hn.gege.im.modules.im.mapper.ChatMessageMapper;
import com.hn.gege.im.modules.im.service.IChatMessageService;
import com.hn.gege.im.modules.im.service.IChatMessageUnreadService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * <p>
 * 聊天消息 服务实现类
 * </p>
 *
 * @author zxy
 * @since 2021-10-12
 */
@Service
public class ChatMessageServiceImpl extends ServiceImpl<ChatMessageMapper, ChatMessage> implements IChatMessageService {

    @Autowired
    private IChatMessageUnreadService chatMessageUnreadService;

    @Override
    public boolean add(ChatMessage chatMessage) {
        return super.save(chatMessage) ;
    }

    @Override
    public Page<ChatMessage> listPage(String msgId, Integer limit, String sender, String receiver) {
        Page<ChatMessage> pageInfo = new Page<>(1, limit);
        LambdaQueryWrapper<ChatMessage> lambda = new QueryWrapper<ChatMessage>().lambda()
                .eq(ChatMessage::getSender, sender)
                .eq(ChatMessage::getReceiver, receiver)
                .or(i -> i.eq(ChatMessage::getSender, receiver).eq(ChatMessage::getReceiver, sender))
                .orderByDesc(ChatMessage::getMsgId);

        //通过msgId,获取这条消息之前的
        if ( ! StringUtils.isEmpty(msgId)){
            lambda.gt(ChatMessage::getMsgId, msgId);
        }
        return super.page(pageInfo, lambda);
    }


    @Override
    public String checkFileMD5(String md5) {
        String content = "%" + md5 + "%";
        LambdaQueryWrapper<ChatMessage> qw = new QueryWrapper<ChatMessage>().lambda()
                .like(ChatMessage::getContent, content);
        List<ChatMessage> list = super.list(qw);
        if (list == null || list.size() == 0) {
            return null;
        }
        return list.get(0).getContent();
    }
}
